package com.abcgz.grade.config;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.servlet.AdviceFilter;
import org.springframework.util.StringUtils;

import com.abcgz.grade.dao.User;
import com.abcgz.grade.model.RestResult;
import com.alibaba.fastjson.JSON;

public class MyAuthenticationFilter extends FormAuthenticationFilter {
	
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        
        String uri = httpServletRequest.getRequestURI();
        if(uri.startsWith("/static") || uri.startsWith("/login") 
        		|| uri.startsWith("/ajaxlogin") || uri.startsWith("/403")
        		|| uri.startsWith("/gradeResult")|| uri.startsWith("/getInnovateResult")|| uri.startsWith("/result")
        		|| uri.startsWith("/list")|| uri.startsWith("/manage")|| uri.startsWith("/enableGrade")
        		|| uri.startsWith("/innovate")|| uri.startsWith("/getInnovateItem")|| uri.startsWith("/info")) {
        		return true;
        }
        
        Subject subject = SecurityUtils.getSubject();
        User sysUser = (User)subject.getPrincipal();
        if (null == sysUser) {
            String requestedWith = httpServletRequest.getHeader("X-Requested-With");
            if (!StringUtils.isEmpty(requestedWith) && requestedWith.equals("XMLHttpRequest")) {//如果是ajax返回指定数据
            		RestResult output = new RestResult(false , "登录状态已失效，请重新登录");
                httpServletResponse.setCharacterEncoding("UTF-8");
                httpServletResponse.setContentType("application/json");
                httpServletResponse.getWriter().write(JSON.toJSONString(output));
                return false;
            } else {//不是ajax进行重定向处理
                httpServletResponse.sendRedirect("/login");
                return false;
            }
        }
        return true;
	}

}